import Logger from "../../../log/Logger";
import { FileInfo, FileUploadConfig, FileUploadListener } from "../FileServerClient";
import AbstractClient from "./AbstractClient";
import Beans from "../../../common/utils";


/**
 *  plupload文件上传客户端.
 *  适用SDK 平台: WEB
 *  配置方式
    sdkConfig.fileServerConfig = {
        use: 'aliyun',
        // use: 'local',
        client: 'plupload',
        baseUrl: 'http://192.168.0.100:8082',
        version: 'v1',
    };
 *
 * */
export  default class PluploadClient extends AbstractClient{
    upload(path:string):string{
        throw new Error('Not support the method, please use fetchClient.');
    }

    public init(uploadConfig: FileUploadConfig, listeners: FileUploadListener|undefined): void {
        const plupload = require('plupload');
        const self = this;
        self.uploadConfig = uploadConfig;
        if(listeners !== undefined){
            this.beforeUploadCallback = listeners.beforeUploadCallback;
            this.progressCallback = listeners.progressCallback;
            this.uploadedCallback = listeners.uploadedCallback;
            this.errorCallback = listeners.errorCallback;
        }
        const uploaderFilter = {
            max_file_size : uploadConfig.maxFileSize + 'mb', //最大只能上传 xx mb的文件
            prevent_duplicates : false //允许选取重复文件
        };
        if(uploadConfig.allowSuffix && uploadConfig.allowSuffix.length > 0){
            uploaderFilter['mime_types'] = [{
                title : "FILE SUFFIX", extensions : uploadConfig.allowSuffix.join(",")
            }]
        }
        self.uploader = new plupload.Uploader({
            runtimes : 'html5,html4',
            browse_button : uploadConfig.domId,
            url : 'http://oss.aliyuncs.com',
            filters: uploaderFilter,
            init: {
                PostInit: function() {
                },
                FilesAdded: function(up, files) {
                    if(files.length > 1){
                        self.setErrorCallback(700, "一次仅能上传一个文件");
                        return;
                    }
                    const file = files[0];
                    const info = new FileInfo();
                    info.id = file.id;
                    info.name = file.name;
                    info.originFileName = file.name;
                    info.size = parseFloat(parseFloat(file.size/1024+'').toFixed(0));
                    info.type = self.getFileType(file.name);
                    if(typeof self.beforeUploadCallback === 'function'){
                        const customInfo = self.beforeUploadCallback(info);
                        if(customInfo){
                            self.fileInfo = customInfo;
                        }
                        else {
                            self.fileInfo = info;
                        }
                    }
                    else {
                        self.fileInfo = info;
                    }
                    self.startUploadWithSign(up);
                },

                BeforeUpload: function(up, file) {
                },

                UploadProgress: function(up, file) {
                    if(typeof self.progressCallback === 'function'){
                        if(self.fileInfo){
                            self.fileInfo.uploadPercent = file.percent;
                            self.progressCallback(self.fileInfo);
                        }
                    }
                },
                FileUploaded: function(up, file, info) {
                    if (info.status == 200 && self.fileInfo !== undefined && self.signInfo !== undefined)
                    {
                        self.sendSyncUploadCallback({
                            filename: self.signInfo.dir,
                            originFileName: self.fileInfo.originFileName,
                            fileType: self.fileInfo.type
                        }).then((resp=>{
                            if(typeof self.uploadedCallback === 'function' && self.fileInfo !== undefined && self.signInfo !== undefined){
                                self.fileInfo.uploadPercent = 100;
                                self.fileInfo.url = self.getDownloadUrl(info);
                                self.uploadedCallback(self.fileInfo);
                            }
                        })).catch(e =>{
                            Logger.trace(e)
                            self.setErrorCallback(701, e+"");
                        });
                    }
                    else if (info.status == 203)
                    {
                        self.setErrorCallback(703, '上传到OSS成功，但是oss访问用户设置的上传回调服务器失败，失败原因是:' + info.response);
                    }
                    else
                    {
                        self.setErrorCallback(704, info.response);
                    }
                },
                Error: function(up, err) {
                    if (err.code == -600) {
                        self.setErrorCallback(600, "选择的文件太大了,可以根据应用情况，在upload.js 设置一下上传的最大大小");
                    }
                    else if (err.code == -601) {
                        self.setErrorCallback(601, "选择的文件后缀不对,可以根据应用情况，在upload.js进行设置可允许的上传文件类型");
                    }
                    else if (err.code == -602) {
                        self.setErrorCallback(602, "这个文件已经上传过一遍了");
                    }
                    else
                    {
                        self.setErrorCallback(602, "Error xml:" + err.response);
                    }
                }
            }
        });
        self.uploader.init();
    }

    // 开始上传文件
    // private startUploadWithSign = function(up)
    private startUploadWithSign:(up:any)=>void = (up) =>
    {
        const self = this;
        self.buildFormParams(self.fileInfo, function (host, formData) {
            let uploadUrl = '';
            if(self.serverConfig.use === 'local'){
                uploadUrl = (self.serverConfig.baseUrl + '/' + self.serverConfig.version + '/' + 'common/file/upload');
            }
            else if(self.serverConfig.use === 'aliyun'){
                uploadUrl = host;
            }
            up.setOption({
                'url': uploadUrl,
                'multipart_params':formData
            });
            up.start();
        })
    };

    private getDownloadUrl(response:any){
        const jsonBody = Beans.bean(response.response);
        if(this.serverConfig.use === 'local'){
            return jsonBody.code === 0 ? jsonBody.data.url : '';
        }else if(this.serverConfig.use === 'aliyun'){
            return this.signInfo.host + '/' + this.signInfo.dir;
        }
        return '';
    }


}
